package cc.messcat.web.fupin;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.circle.Comment;
import cc.messcat.entity.circle.WorkCircle;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.fupin.CommentService;
import cc.messcat.service.fupin.WorkCircleService;
import cc.messcat.service.system.UserService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;

/**
 * 工作圈控制层 
 */
@Controller
@RequestMapping("/circle")
public class WorkCircleController {
	static Logger log = LoggerFactory.getLogger("工作圈");

	@Autowired
	private WorkCircleService workCircleService;
	
	@Autowired
	private CommentService commentService;

	@Autowired
	private UserService userService;
	
	private String imgPath = "/img/circle";

	/**
	 * 添加内容
	 */
	@OperationLog(desc="发表工作圈",module="app")
	@RequestMapping(value = "/addCircle", method = RequestMethod.POST)
	@ResponseBody
	public Object addCircle(@RequestParam(name = "imgs") MultipartFile[] imgs, 
		@RequestParam(name = "content") String content,
		@RequestParam(name = "tag",required=true) String tag,
		@RequestParam(name = "location",required=true) String location,
		@RequestParam(name = "lng",required=true) Double lng,
		@RequestParam(name = "lat",required=true) Double lat,
		HttpSession session, HttpServletRequest request) throws Exception {

		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		
		if(imgs != null && imgs.length>9) {
			return new ResponseBean(CommonConstant.FAIL_CODE_400, "最多上传9张图片", null);
		}
		
		//处理文件上传
		StringBuilder url = new StringBuilder("");
		String realPath = session.getServletContext().getRealPath(imgPath);
        Random random = new Random();
        for (int i = 0; i < imgs.length;i++) {
            MultipartFile img = imgs[i];
			if (img.isEmpty()) {
				log.warn("文件未上传");
			} else {
				String fileName = img.getOriginalFilename();
				fileName = "/c"+"-"+user.getId()+"-" + System.currentTimeMillis() + "-" + (random.nextInt(9000) + 1000) +i +"." + FilenameUtils.getExtension(fileName);
				url.append(session.getServletContext().getContextPath() + imgPath + fileName + ",");
				FileUtils.copyInputStreamToFile(img.getInputStream(), new File(realPath, fileName));
			}
		}
		WorkCircle circle = new WorkCircle(null, content,
			StringUtils.isNotBlank(url.toString()) ? url.toString().substring(0, url.length() - 1) : "", "", new Date(), user,tag,location,lng,lat,null);
        Long id = workCircleService.addCircle(circle);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "发布成功", id);
	}
	
	/**
	 * 删除内容
	 */
	@RequestMapping(value = "/removeCircle", method = RequestMethod.POST)
	@ResponseBody
	public Object removeCircle(@RequestParam(name="circleId",required=true)final Long circleId,HttpSession session, HttpServletRequest request) throws IOException {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		
		WorkCircle circle = workCircleService.retrieveObject(circleId);
		
		if(circle != null) {
			if(!circle.getUser().getId().equals(user.getId())) {
				return new ResponseBean(CommonConstant.FAIL_CODE_400, "无法删除他人的动态", null);
			}
			final String imgs = circle.getPictures();
			workCircleService.removeObject(circleId);
			
			//动态图片删除
			try {
				new Thread(new Runnable() {
					@Override
					public void run() {
						log.info("删除工作圈图片 {id="+circleId+"}");
						for(final String img : imgs.split(",")) {
							ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
							File file = new File(servletContext.getRealPath(imgPath));
							if(file.listFiles() == null) return;
							for(File f : Objects.requireNonNull(file.listFiles(new FilenameFilter() {
                                @Override
                                public boolean accept(File dir, String name) {
                                    return img.substring(img.lastIndexOf("/") + 1).equals(name);
                                }
                            }))) {
								f.delete();
							}
						}
					}
				}).start();
			} catch (Exception e) {
				log.warn("工作圈图片删除失败");
				e.printStackTrace();
			}
		}
		
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "删除成功", null);
	}
	
	/**
	 * 获取内容
	 */
	@RequestMapping(value = "listCircle")
	@ResponseBody
	@SuppressWarnings("all")
	public Object listCircle(
		@RequestParam(name = "pageNo",required=false)Integer pageNo,
		@RequestParam(name = "pageSize",required=false)Integer pageSize,
        //默认为false，如果为true则只列出当前登录用户的内容
		@RequestParam(name = "circleManagement",required=false,defaultValue="false")Boolean circleManagement,
        //用户id,列出指定用户的内容，默认为null,如果有circleManagement参数则忽略此参数
		@RequestParam(name = "userId",required=false)Long userId,
		WorkCircle circle,
		HttpSession session, HttpServletRequest request) {

		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
		pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;
		
		//分为列出所有用户，指定用户和列出当前用户的动态
		Pager<WorkCircle> page = circleManagement 
			? workCircleService.listCircle(pageNo, pageSize,user.getId(),circle)
			: userId == null ? workCircleService.listCircle(pageNo,pageSize,circle)
			: workCircleService.listCircle(pageNo,pageSize,userId,circle);
			
		Map<Long,String> commentMap = new HashMap<>();
		List<Map<String,Object>> result = new ArrayList<>(pageSize);
		for(WorkCircle c : (List<WorkCircle>)page.getResultList()) {
			String praiseCase = "false";
			StringBuilder sb = new StringBuilder();
			c.getUser().setRoles(null);

            if (StringUtils.isNotBlank(c.getPraise())) {
                List<Map<String,Object>> users = userService.listByIDs(c.getPraise());
                for (Map<String,Object> u : users) {
                    sb.append((StringUtils.isNotBlank((String)u.get("realName")) ? u.get("realName").toString() : u.get("username")) + ",");

                    //判断当前用户是否已点赞该动态
                    if (user.getId().equals(((BigInteger)u.get("id")).longValue())) {
                        praiseCase = "true";
                    }
                }
            }
            c.setPraise(StringUtils.isNotBlank(sb.toString()) ? sb.toString().substring(0, sb.length()-1) : "");
            HashMap<Long,Long> idMap = new HashMap<>();
			for(Comment comment : c.getComment()) {
                idMap.put(comment.getId(),comment.getOwner());
                commentMap.put(comment.getId(),"未知用户");
			}
            String commentOwnerIDs = Arrays.toString(idMap.values().toArray()).replaceAll("[\\[\\]]", "");
			if(StringUtils.isNotBlank(commentOwnerIDs)) {
                List<Map<String, Object>> commentOwner = userService.listByIDs(commentOwnerIDs);
                HashMap<Long,String> userMap = new HashMap<>();
                for(Map<String,Object> e : commentOwner) {
                    String name = StringUtils.isNotBlank((String)e.get("realName")) ? e.get("realName").toString() : e.get("username").toString();
                    userMap.put(((BigInteger)e.get("id")).longValue(),name);
                }
                for(Map.Entry<Long,Long> entry : idMap.entrySet()) {
                    commentMap.put(entry.getKey(),userMap.get(entry.getValue()));
                }
            }

            List<Map> commentList = new ArrayList<>();
			for(Comment comment : c.getComment()) {
				Map commentResult = new HashMap<>();
				commentResult.put("id", comment.getId());
				commentResult.put("workCircleId", comment.getWorkCircleId());
				commentResult.put("content", comment.getContent());
				commentResult.put("editTime", comment.getEditTime());
				commentResult.put("owner", comment.getOwner());
				commentResult.put("belong", comment.getBelong());
				commentResult.put("replyer", commentMap.get(comment.getId()));
				commentResult.put("receiver", "");
				if(comment.getBelong() != null) {
					commentResult.put("receiver", commentMap.get(comment.getBelong()));
				} 
				commentList.add(commentResult);
			}
			
			Map<String, Object> map = cc.messcat.util.Collections.generateHashMap(
				"id", c.getId(),
				"content", c.getContent(),
				"pictures", c.getPictures(),
				"editTime", c.getEditTime(),
				"praise", c.getPraise(),
				"praiseCase", praiseCase,
				"ownerId", c.getUser().getId(),
				"ownerUserName", c.getUser().getUsername(),
				"ownerRealName", c.getUser().getRealName(),
				"comment", commentList,
				"tag", c.getTag(),
                "location",c.getLocation(),
                "lng",c.getLng(),
                "lat",c.getLat()
				);
			
			result.add(map);
		}
		
		page = new Pager(page.getPageSize(),page.getPageNo(),page.getRowCount(),result);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,page );
	}
	
	/**
	 * 评论
	 */
	@RequestMapping(value = "comment")
	@ResponseBody
	public Object comment(Long commentId,@RequestParam(name="circleId",required=true)Long circleId,String commentContent,
		HttpSession session, HttpServletRequest request) {
		
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		
		if(commentId != null && commentService.retrieveObject(commentId) != null) {
			Comment comment = new Comment(null,circleId,commentContent,new Date(),user.getId(),commentId);
			commentService.addObject(comment);
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "回复成功",null );
		} else {
			Comment comment = new Comment(null,circleId,commentContent,new Date(),user.getId(),null);
			commentService.addObject(comment);
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "评论成功",null );
		}
		
	}
	
	/**
	 * 撤销评论
	 */
	@RequestMapping(value = "deComment")
	@ResponseBody
	public Object deComment(Long commentId,HttpSession session, HttpServletRequest request) {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		
		Comment comment = commentService.retrieveObject(commentId);
		if(comment != null ) {
			if(!comment.getOwner().equals(user.getId())) {
				return new ResponseBean(CommonConstant.FAIL_CODE_400, "不能撤销他人的评论",null );
			}
			commentService.removeObject(commentId);
		}
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "撤销成功",null );
	}
	
	
	/**
	 * 点赞 
	 */
	@RequestMapping(value = "praise")
	@ResponseBody
	public Object praise(@RequestParam(name="circleId")Long circleId,HttpSession session, HttpServletRequest request) {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
	
		WorkCircle circle = workCircleService.retrieveObject(circleId);
		String praise = circle.getPraise();
		for (String s : praise.split(",")) {
			if(s.equals(user.getId().toString())) {
				return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "已经点赞",null );
			}
		}
		
		circle.setPraise(StringUtils.isNotBlank(praise) ? praise + ","+ user.getId().toString() : user.getId().toString());
		workCircleService.modifyObject(circle);
		
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "点赞成功",null );
	}
	
	/**
	 * 取消点赞 
	 */
	@RequestMapping(value = "dePraise")
	@ResponseBody
	public Object dePraise(@RequestParam(name="circleId",required=true)Long circleId,HttpSession session, HttpServletRequest request) {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
	
		WorkCircle circle = workCircleService.retrieveObject(circleId);
		String praise = circle.getPraise();
		if(StringUtils.isBlank(praise)) {
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "已经取消",null );
		}
		StringBuilder newPraise = new StringBuilder();
		for (String s : praise.split(",")) {
			if(s.equals(user.getId().toString())) {
				continue;
			}
			newPraise.append(s+",");
		}
		
		circle.setPraise(StringUtils.isNotBlank(newPraise.toString()) ? newPraise.toString().substring(0, newPraise.length()-1) : "");
		workCircleService.modifyObject(circle);
		
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "取消成功",null );
	}
	
	

}
